/**
 * cyw.com Inc.
 * Copyright (c) 2014-2015 All Rights Reserved.
 */
package com.rainbow.bam.core;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.rainbow.bam.util.StringUtil;

/**
 * 
 * 查询条件filter
 * 
 * @author HarrisonHan
 * @version $Id: SearchFilter.java, v 0.1 2015年10月26日 上午11:17:14 HarrisonHan Exp $
 */
public class SearchFilter {

    public enum Operator {
        EQ, LIKE, GT, LT, GTE, LTE
    }

    public String   fieldName;
    public Object   value;
    public Operator operator;

    public SearchFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.value = value;
        this.operator = operator;
    }

    /**
     * searchParams中key的格式为OPERATOR_FIELDNAME
     */
    public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        for (Entry<String, Object> entry : searchParams.entrySet()) {
            // 过滤掉空值
            String key = entry.getKey();
            Object value = entry.getValue();
            if (StringUtil.isBlank((String) value)) {
                continue;
            }
            // 拆分operator与filedAttribute
            String[] names = StringUtil.split(key, "_");
            if (names.length != 2) {
                throw new IllegalArgumentException(key + " is not a valid search filter name");
            }
            String filedName = names[1];
            Operator operator = Operator.valueOf(names[0]);
            // 创建searchFilter
            SearchFilter filter = new SearchFilter(filedName, operator, value);
            filters.put(key, filter);
        }
        return filters;
    }
}
